package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {
    //套餐菜品关系表
    @Autowired
    private  SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @CacheEvict(value = "setmealCache", allEntries = true)
    @PostMapping
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto){

        log.info("套餐信息:{}",setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    //1.创造分页构造器，传入page pagesize ，根据名字模糊查询数据后再根据修改时间查询数据
//调用service层查询
//2.创造构造器，将之前查询的数据pageInfo拷贝到构造器dtoPage中
//因为pageInfo里面的records和dtoPage里面的不一样，所以排除records拷贝
//3.通过pageinfo的getRecords获取里面的数据列表集合
//再通过records的stream流把分类ID获取出来。
//然后用categoryService的getById方法把分类ID放进去活得分类的对象
//判断对象不为空后通过对象获取出分类对象的名称，在用新建的构造器调用setCategoryName
//把分类对象的名称放进去，存储姓名，最后return回去，并收集最后的集合。最后在把集合放到records里，这样dtoPage里面的数据就完全了
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page>page(int page,int pageSize,String name){
        //分页构造器对象
        Page<Setmeal>pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Setmeal::getName,name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto>list = records.stream().map((item)->{

            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

/**
 * 删除套餐
 * @param ids
 * @return
 */

@CacheEvict(value = "setmealCache", allEntries = true)
@DeleteMapping
@ApiOperation(value = "删除套餐接口")
    public R<String> delete(@RequestParam List<Long>ids){

    log.info("ids:{}",ids);

    setmealService.removeWithDish(ids);
    return R.success("套餐数据删除成功");
   }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
   @GetMapping("/list")
   @Cacheable(value = "setmealCache",key = "#setmeal.categoryId +'_'+#setmeal.status ")
   @ApiOperation(value = "根据条件查询套餐数据接口")
    public R<List<Setmeal>>list(Setmeal setmeal){

    LambdaQueryWrapper<Setmeal>queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(setmeal.getCategoryId()!=null, Setmeal::getCategoryId,setmeal.getCategoryId());
    queryWrapper.eq(setmeal.getStatus() != null , Setmeal::getStatus,setmeal.getStatus());

       List<Setmeal> list = setmealService.list(queryWrapper);
       return  R.success(list);

   }

//    根据ID查询套餐及套餐菜品信息
//    修改套餐及套餐菜品信息

@GetMapping("/{id}")
    public R<SetmealDto>get(@PathVariable Long id){
    SetmealDto setmealDto = setmealService.getByIdWithDish(id);
       return  R.success(setmealDto);
}




    //修改套餐及套餐菜品信息

//    @PutMapping
//    public R<String>update(@RequestBody SetmealDto setmealDto){
//    setmealService.UpdateWithDish(setmealDto);
//    return R.success("修改套餐成功");
//}


@PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.UpdateWithDish(setmealDto);
        return R.success("修改成功");
    }



    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids){
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.set(Setmeal::getStatus,status);
        setmealService.update(wrapper);
        return R.success("修改状态成功");
    }

}

